<script lang="ts" setup>
import { ref, defineExpose, watch, defineAsyncComponent } from 'vue'
import { useEventBus } from '@/utils/eventBus'
import { addCart } from '@/service/goods/cart/cart'
import type { GoodsCart } from '@/service/goods/cart/cart.d'
import { useToast } from 'wot-design-uni'
import { getGoodsDetail } from '@/service/goods/index'
import type { GoodsSku } from '@/service/goods/goods'
import { getAddressDefault } from '@/service/user/address'
import type { CustomAddressVo } from '@/service/user/address.d'
import { useUserStore } from '@/store/user'
import { debounce } from 'lodash-es'
import { calculateBestDiscount } from '@/service/goods/coupon/coupon'
import type { CartItems } from '@/service/goods/coupon/coupon.d'
import { useActiveCartStore } from '@/store/activeCart'
import { useActiveAddressStore } from '@/store/activeAddress'
import { PayTypeEnum } from '@/service/order/orderEnum.d'
import { formatMoney } from '@/utils/index'

const ProductSku = defineAsyncComponent(() => import('@/components/product/prodct-sku.vue'))
const DiscountBox = defineAsyncComponent(() => import('@/components/discountBox/index.vue'))
const PayMent = defineAsyncComponent(() => import('@/components/payment/index.vue'))

const AddressPicker = defineAsyncComponent(
  () => import('@/components/address/AddressSelector/AddressSelector.vue'),
)
const activeCart = useActiveCartStore()
const activeAddress = useActiveAddressStore()
/**
 * buy 购买模式
 * cart 购物车模式  cart

 */
const props = defineProps({
  modelType: {
    type: String as PropType<'cart' | 'buy'>,
    required: true,
    default: 'buy',
    validator: (value: string) => ['cart', 'buy'].includes(value),
  },
})

interface GoodsSkuData extends GoodsSku {
  quantity: number
}
const userStore = useUserStore()
const emit = defineEmits(['popClose', 'updateCartSpec'])
const { emitts } = useEventBus()
// import PriceDetailPopup from './price-detail-popup.vue'
const { loading, close } = useToast()
const show = ref(false)
const activeSkuId = ref<number | string>()
const activeGoodsId = ref<number | string>()
const activeSkuData = ref<GoodsSkuData>()
const defaultAddress = ref<CustomAddressVo>()
const GoodsSkuList = ref<GoodsSku[]>([])
const quantityValue = ref<number>(1)
const paymentType = ref<PayTypeEnum>(PayTypeEnum.ALIPAY)

const getGoodsDetailData = debounce(async (id: number | string) => {
  const { code, data } = await getGoodsDetail(String(id))
  if (code === 200 && data) {
    GoodsSkuList.value = data?.goodsSkuList || []
    const newIndex = GoodsSkuList.value.findIndex((item) => item.id === activeSkuId.value)
    activeSkuData.value = { ...GoodsSkuList.value[newIndex], quantity: 1 }
  }
  console.log(data)
}, 200)

watch(
  () => quantityValue.value,
  (newVal) => {
    activeSkuData.value.quantity = newVal
  },
)

const getAddressDefaultData = debounce(async () => {
  const { code, data } = await getAddressDefault()
  if (code === 200 && data) {
    console.log(data)
    defaultAddress.value = data
  }
}, 200)
const discountList = ref<any[]>([])
const totalPrice = ref(0)
watch(
  () => activeSkuData.value,
  debounce((newVal) => {
    console.log('带防抖的监听器（500ms防抖间隔）')
    console.log(props.modelType)
    console.log(newVal)

    if (newVal === null && newVal === undefined) return

    if (newVal !== null && props.modelType === 'buy' && show.value) {
      console.log('带防抖的监听器（500ms防抖间隔）', newVal)
      discountList.value = []
      const obj: CartItems = {
        skuId: newVal.id,
        quantity: newVal.quantity,
      }
      totalPrice.value = 0
      loading('加载中')
      // 计算优惠
      calculateBestDiscount({
        userId: Number(userStore.userInfo.id),
        cartItems: [obj],
      }).then((res) => {
        console.log(res)
        if (res.code === 200 && res.data) {
          discountList.value = res.data
          console.log(discountList)
          discountList.value.forEach((item) => {
            totalPrice.value += Number(
              Number((item.originalPrice * item.quantity).toFixed(2)) - item.discountAmount,
            )
          })
        } else {
          throw new Error('暂无优惠')
        }
      })

      close()
    }
  }, 100),
  { deep: true },
)
const handleClose = () => {
  emit('popClose')
  show.value = false
  emitts('add-tabbar-event')
  activeGoodsId.value = null
  activeSkuId.value = null
  GoodsSkuList.value = []
  activeSkuData.value = {} as GoodsSkuData
}
const hanleOpen = (skuId: number | string, goodsId: number | string) => {
  console.log(skuId, goodsId)
  activeGoodsId.value = goodsId
  activeSkuId.value = skuId
  emitts('cancel-tabbar-event')
  getGoodsDetailData(goodsId)
  if (props.modelType === 'buy') {
    getAddressDefaultData() // 获取默认地址
  }

  show.value = true
}
defineExpose({ hanleOpen, handleClose })
const showPriceDetail = ref(false)

const beforeChange = (value) => {
  loading({ msg: `加载中...` })
  return new Promise((resolve) => {
    setTimeout(() => {
      close()
      resolve(true)
    }, 500)
  })
}

const switchSku = (skuId: number, index: number) => {
  activeSkuId.value = skuId
  activeSkuData.value = { ...GoodsSkuList.value[index], quantity: 1 }
  console.log(activeSkuData.value)
}

// 计算总价

const MarketTotalPrice = computed(() =>
  Number((activeSkuData.value?.marketPrice * activeSkuData.value?.quantity).toFixed(2)),
)

const handleAddCart = async () => {
  const obj: GoodsCart = {
    goodsId: activeGoodsId.value as number,
    skuId: activeSkuId.value as number,
    goodsNum: activeSkuData.value.quantity,
    customerId: Number(userStore.userInfo.id),
    selected: 1,
  }
  try {
    const { code, data } = await addCart(obj)
    if (code === 200 && data) {
      handleClose()
      uni.showToast({ title: '加入购物车成功', icon: 'none' })
    } else {
      uni.showToast({ title: '加入失败', icon: 'none' })
    }
  } catch (error) {
    uni.showToast({ title: '加入失败', icon: 'none' })
  }
}

const handleBuyNow = async () => {
  console.log('立即支付', paymentType.value)
  const obj: GoodsCart = {
    goodsId: activeGoodsId.value as number,
    skuId: activeSkuId.value as number,
    goodsNum: activeSkuData.value.quantity,
    customerId: Number(userStore.userInfo.id),
    selected: 1,
  }
  console.log('立即支付', obj)
  const { code, data } = await addCart(obj)
  if (code === 200 && data) {
    activeCart.setTemporaryCart({ ...obj, id: data })
    handleClose()
    uni.navigateTo({ url: `/pages/order/orderConfirm?now=${true}` })
  } else {
    uni.showToast({ title: '系统异常，请稍后', icon: 'none' })
  }
}

const changeCartSpec = () => {
  emit('updateCartSpec', activeSkuData.value.quantity, activeSkuData.value)
  handleClose()
}
const priceInfo = ref<boolean>(false)

const addressPicker = ref()

const openAddressPicker = () => {
  console.log(111)
  addressPicker.value.handleOpen()
}

const onAddressSelect = (address: CustomAddressVo) => {
  console.log('选中的地址:', address)
  defaultAddress.value = address
  activeAddress.setActiveAddress(address)
}

const updatePayment = (e) => {
  console.log(e)
  const value = e.value
  switch (value) {
    case PayTypeEnum.WXPAY:
      paymentType.value = PayTypeEnum.WXPAY
      break
    case PayTypeEnum.ALIPAY:
      paymentType.value = PayTypeEnum.ALIPAY
      break
    case PayTypeEnum.BALANCE:
      paymentType.value = PayTypeEnum.BALANCE
      break
    default:
      console.warn('无效的支付类型')
      break
  }
}
</script>
<template>
  <view class="one-popup">
    <wd-popup
      v-model="show"
      lock-scroll
      position="bottom"
      custom-style="height: auto;max-height:calc(100vh - 300rpx);"
      @close="handleClose"
    >
      <view class="popup-continer">
        <!-- 地址选择栏 -->
        <view class="address-top" v-if="props.modelType != 'cart'">
          <view class="address-card" v-if="props.modelType === 'buy' && defaultAddress">
            <view class="flex justify-between">
              <view>
                <text class="title">{{ defaultAddress.fullAddress + defaultAddress.address }}</text>
                <view class="address-info">
                  <text class="text">{{ defaultAddress.name }}</text>
                  <text class="text">{{ defaultAddress.phone }}</text>
                </view>
              </view>
              <wd-icon name="arrow-right" size="18px" color="#666" @click="openAddressPicker" />
            </view>
          </view>
          <view class="address-card" v-else>
            <view class="flex justify-between" @click="openAddressPicker">
              <view style="font-size: 36rpx">请选择收货地址</view>
              <wd-icon name="arrow-right" size="18px" color="#666" />
            </view>
          </view>
        </view>
        <!-- 主要内容区域 -->
        <view class="popup-info">
          <scroll-view scroll-y class="scroll-area">
            <!-- 商品信息 -->
            <view class="info-section">
              <view class="goods-header">
                <view class="goods-thumb">
                  <image-container :src="activeSkuData?.thumbImg"></image-container>
                </view>
                <view class="goods-info">
                  <view class="goods-title">{{ activeSkuData?.skuName }}</view>
                  <view>
                    <text class="goods-price">¥{{ activeSkuData?.salePrice }}</text>
                    <text class="goods-maketPrice">¥{{ activeSkuData?.marketPrice }}</text>
                  </view>
                </view>
              </view>
              <!-- <view></view> -->
              <view class="specs-section">
                <text class="section-title">选择规格</text>
                <view>
                  <scroll-view scroll-x>
                    <view class="product-list">
                      <ProductSku
                        @click="switchSku(sku.id, index)"
                        v-for="(sku, index) in GoodsSkuList"
                        :key="sku.id"
                        :skuItem="sku"
                        :selected="activeSkuId == sku.id"
                      />
                    </view>
                  </scroll-view>
                </view>
              </view>
            </view>

            <!-- 数量选择 -->
            <view class="info-section">
              <view class="quantity-picker">
                <text>数量</text>

                <view class="counter">
                  <wd-input-number v-model="quantityValue" :before-change="beforeChange" />
                </view>
              </view>
            </view>

            <!-- 支付方式 -->
            <!-- <view class="info-section" >
              <text class="section-title">支付方式</text>
              <wd-radio-group v-model="paymentType" checked-color="#ff5f15" shape="dot">
                <view class="payment-option">
                  <wd-radio value="alipay" style="width: 100%">
                    <view class="left">
                      <view style="font-size: 54rpx" class="icon-zhifubaozhifu iconfont"></view>
                      <text style="font-size: 28rpx">支付宝</text>
                    </view>
                  </wd-radio>
                </view>
                <view class="payment-option">
                  <wd-radio value="wechat" style="width: 100%">
                    <view class="left">
                      <view style="font-size: 48rpx" class="icon-zhifu-weixinzhifu iconfont"></view>
                      <text style="font-size: 28rpx">微信支付</text>
                    </view>
                  </wd-radio>
                </view>
              </wd-radio-group>
            </view> -->
            <PayMent
              v-if="modelType === 'buy'"
              :payment-type="paymentType"
              @update:paymentType="updatePayment"
            />
          </scroll-view>
        </view>

        <!-- 底部操作栏 -->
        <view class="action-footer" v-if="modelType === 'buy'">
          <view class="price-summary" @click="showPriceDetail = true">
            <view class="left">
              <view>
                <text>预计到手价</text>
                <text class="total">¥{{ formatMoney(totalPrice) }}</text>
              </view>
              <text class="discount">已优惠¥{{ formatMoney(MarketTotalPrice - totalPrice) }}</text>
            </view>
            <!-- <view class="right" @click="handelShowPriceInfo">
              <text>价格明细</text>
              <wd-icon name="arrow-up" />
            </view> -->
          </view>
          <view class="action-buttons">
            <view class="action-box">
              <view class="action-cart" @click="handleAddCart">加入购物车</view>
              <view class="action-buy" @click="handleBuyNow">立即支付</view>
            </view>
          </view>
        </view>
        <view class="action-cart-confim" v-if="modelType === 'cart'" @click="changeCartSpec">
          <view>确认</view>
        </view>
      </view>
    </wd-popup>
    <AddressPicker ref="addressPicker" @select="onAddressSelect" />
    <!-- 价格明细弹窗 -->
    <!-- <DiscountBox :modelValue="priceInfo" /> -->
  </view>
</template>
<style lang="scss" scoped>
.popup-continer {
  z-index: 9999;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 300rpx);
  min-height: auto;
  max-height: calc(100vh - 300rpx);
  background-color: #f5f5f5;
  .address-top {
    padding: 20rpx 30rpx;
    background: #fff;
    .address-card {
      padding: 20rpx;
      background: rgba($uni-bg-themes, 0.1);
      border-radius: 12rpx;
      .title {
        font-size: 32rpx;
        color: #000;
      }
      .address-info {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-top: 15rpx;
        .text {
          font-size: 28rpx;
          color: #333;
        }
      }
    }
  }
}

.popup-info {
  flex: 1;
  height: 600rpx;
  min-height: 500rpx;
  margin: 20rpx 0;
  overflow: hidden;
  border-radius: 20rpx;
  .scroll-area {
    box-sizing: border-box;
    height: 100%;
    min-height: 500rpx;
    padding: 0 20rpx;
  }
}

.specs-section {
  // .section-title {
  //   font-size: 28rpx;
  //   color: #333;
  // }
  .product-list {
    display: flex;
    margin-top: 20rpx;
    white-space: nowrap;
  }
}
.info-section {
  padding: 30rpx;
  margin: 20rpx 0;
  background: #fff;
  border-radius: 12rpx;
  &:first-child {
    margin-top: 0;
  }

  .goods-header {
    display: flex;
    justify-content: space-between;
    width: 660rpx;
    margin-bottom: 30rpx;
    .goods-thumb {
      width: 120rpx;
      height: 120rpx;
      margin-right: 20rpx;
      border-radius: 8rpx;
    }
    .goods-info {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      width: 520rpx;
      .goods-title {
        display: -webkit-box;
        width: 100%;
        overflow: hidden;
        font-size: 28rpx;
        color: #333;
        text-overflow: ellipsis;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
      }
      .goods-price {
        margin-top: 15rpx;
        font-size: 32rpx;
        color: $uni-bg-themes;
      }
      .goods-maketPrice {
        margin-top: 15rpx;
        margin-left: 15rpx;
        font-size: 24rpx;
        color: #999;
        text-decoration: line-through;
      }
    }
  }

  .quantity-picker {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .counter {
      display: flex;
      align-items: center;
      .input {
        width: 80rpx;
        margin: 0 20rpx;
        text-align: center;
      }
    }
  }

  .payment-option {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 25rpx 0;
    .left {
      display: flex;
      gap: 15rpx;
      align-items: center;
    }
  }
}

.action-footer {
  z-index: 999;
  padding: 20rpx 30rpx;
  background: #fff;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);
  .price-summary {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-bottom: 20rpx;
    .left {
      .total {
        margin-right: 20rpx;
        font-size: 32rpx;
        color: $uni-bg-themes;
      }
      .discount {
        font-size: 24rpx;
        color: #999;
      }
    }
    .right {
      display: flex;
      align-items: center;
      font-size: 24rpx;
      color: #666;
    }
  }

  .action-buttons {
    display: flex;
    gap: 20rpx;
    justify-content: center;
    .action-box {
      display: flex;
      justify-content: center;
      width: 680rpx;
      height: 80rpx;
      overflow: hidden;
      line-height: 80rpx;
      color: #fff;
      text-align: center;
      // background-color: red;
      border-radius: 50rpx;
      .action-cart {
        width: 340rpx;
        height: 80rpx;
        background: linear-gradient(-90deg, #515155, #1a1a1a);
        // background-color: rebeccapurple;
      }
      .action-buy {
        width: 340rpx;
        height: 80rpx;
        background-color: $uni-bg-themes;
      }
    }
  }
}
.action-cart-confim {
  box-sizing: border-box;

  padding: 10rpx;
  margin: 20rpx;
  font-size: 32rpx;
  line-height: 2;
  color: #fff;
  text-align: center;
  background-color: red;
  border-radius: 60rpx;
}
</style>
